package com.example.demoback.web;

import com.example.demoback.entity.Result;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestPart;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.util.UUID;

@RestController
public class IndexAction {
    @RequestMapping("hello")
    public String hello(String name) {
        return "hello " + name;
    }

    @Value("${upload.diskPath}")
    String diskPath;
    @Value("${upload.webPath}")
    String webPath;

    @RequestMapping("/upload")  // 明确指定 POST 方法 + 全小写路径
    public Result upload(@RequestPart("file") MultipartFile uploadFile) {
        try {
            // 校验文件是否为空
            if (uploadFile.isEmpty()) {
                return new Result(0, "文件不能为空", null);
            }

            // 生成唯一文件名
            String originalFilename = uploadFile.getOriginalFilename();
            String suffix = originalFilename.substring(originalFilename.lastIndexOf("."));
            String newFileName = UUID.randomUUID() + suffix;

            // 确保目录存在
            File uploadDir = new File(diskPath);
            if (!uploadDir.exists()) {
                uploadDir.mkdirs();
            }

            // 安全保存文件（自动处理路径斜杠）
            File diskFile = new File(uploadDir, newFileName);
            uploadFile.transferTo(diskFile);

            String webFile = "http://127.0.0.1:5920" + webPath + newFileName;
            System.out.println("Disk Path: " + diskPath);

            return new Result(1, "文件上传成功", webFile);
        } catch (IOException e) {
            e.printStackTrace();
            return new Result(0, "文件上传失败: " + e.getMessage(), null);
        }

    }
}